package xyz.zhouzhaodong.transactional.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import xyz.zhouzhaodong.transactional.entity.User;
import xyz.zhouzhaodong.transactional.mapper.UserMapper;

import javax.annotation.Resource;

/**
 * @author zhouzhaodong
 */
@Service
public class TestServiceImpl {

    @Resource
    UserMapper userMapper;

    @Transactional(rollbackFor = Exception.class)
    void twoTestNoPublic(){
        // 插入一条数据
        int num = userMapper.insert(new User("小红", "青岛市", 18));
        if (num > 0){
            // 插入后制造一个错误
            System.out.println(1 / 0);
        }
        // 再次插入一条数据
        userMapper.insert(new User("小强", "烟台市", 21));
    }

    @Transactional(rollbackFor = Exception.class)
    public void threeTestNoPublic(){
        // 插入一条数据
        int num = userMapper.insert(new User("小红", "青岛市", 18));
        if (num > 0){
            try {
                // 插入后制造一个错误
                System.out.println(1 / 0);
            } catch (Exception e) {
                e.printStackTrace();
                return;
                // 在catch里面进行回滚
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        // 再次插入一条数据
        userMapper.insert(new User("小强", "烟台市", 21));
    }
}
